#include "parameter.h"

ParameterReader::ParameterReader()
{   
    filename_ = "../config/config.txt";
    std::ifstream fin (filename_.c_str());
    if(!fin)
    {
        std::cerr << "--parameters file does not exist!" << std::endl;
        return;
    }

    while(!fin.eof())
    {
        std::string str;
        std::getline(fin, str);
        // std::cout << str << std::endl;
        {
            if(str[0] == '#')  // 过滤#,#为注
                continue;
        }

        int pos = str.find("="); // 找到=的位置
        if(pos == -1)
            continue;
        
        std::string key = str.substr(0, pos); 
        std::string value = str.substr(pos+1, str.length());
        data[key] = value;

        if(!fin.good())
            break;
        // std::cout << key << ":" << data[key] << std::endl;
    }
}

ParameterReader::ParameterReader(std::string filename):filename_(filename)
{
    std::ifstream fin (filename_.c_str());
    if(!fin)
    {
        std::cerr << "--parameters file does not exist!" << std::endl;
        return;
    }

    while(!fin.eof())
    {
        std::string str;
        std::getline(fin, str);
        // std::cout << str << std::endl;
        {
            if(str[0] == '#')  // 过滤#,#为注
                continue;
        }

        int pos = str.find("="); // 找到=的位置
        if(pos == -1)
            continue;
        
        std::string key = str.substr(0, pos); 
        std::string value = str.substr(pos+1, str.length());
        data[key] = value;

        if(!fin.good())
            break;
        // std::cout << key << ":" << data[key] << std::endl;
    }
}

std::string ParameterReader::getData(std::string key)
{
    std::map<std::string, std::string>::iterator iter = data.find(key);
    if(iter == data.end())
    {
        std::cerr << "--Parameter name:" << key << " not found!" << std::endl;
        return std::string("Not_found");
    }
    return iter->second;
}

